package com.hlbspringcloud.mq;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * @Author huanglibin
 * @Project mq
 * @Description 发布订阅模式 消息消费者一
 * @Date 2020-12-04-09-33-48
 * @Version 1.0
 */
public class publishReceiver1 {
    /**
     * 路由名称
     */
    public static final String ROUNTING_NAME = "publish rounting";
    /**
     * 队列名称
     */
    public static final String PUBLISH_ROUNTING_QUEUE = "publish rounting queue1";

    /**
     * 消费消息
     * @throws Exception
     */
    public static void receiveMessage() throws Exception{
        //1.创建连接
        Connection rabbitmqConnection = RabbitmqUntil.getRabbitmqConnection();
        //2.获取管道
        final Channel channel = rabbitmqConnection.createChannel();
        //3.定义队列
        channel.queueDeclare(PUBLISH_ROUNTING_QUEUE,true,false,false,null);
        //4.设置每次获取消息不超过1条
        channel.basicQos(1);
        //5.将路由和队列进行绑定
        channel.queueBind(PUBLISH_ROUNTING_QUEUE,ROUNTING_NAME,"");
        //6.定义消费用户
        DefaultConsumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                try{
                    System.out.println("消费者1："+new String(body,"utf-8"));
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    channel.basicAck(envelope.getDeliveryTag(),false);
                }
            }
        };
        //7.监听队列消息
        channel.basicConsume(PUBLISH_ROUNTING_QUEUE,false,consumer);
    }

    public static void main(String[] args) throws Exception {
        publishReceiver1.receiveMessage();
    }
}
